package com.wenming.notify;

import com.wenming.library.NotifyUtil;
import com.wenming.notify.iml.OnEnableListener;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.NotificationHelper;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.rpc.RemoteException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class NotifyPageProvider extends PageSliderProvider implements Component.ClickedListener,
        OnEnableListener {
    private final NotifyUtil notifyUtil;

    private Context context;
    private DirectionalLayout mSingLine;
    private DirectionalLayout mMoreLine;
    private DirectionalLayout mMailbox;
    private DirectionalLayout mBigPic;
    private DirectionalLayout mCustomView;
    private DirectionalLayout mButtom;
    private DirectionalLayout mProgress;
    private DirectionalLayout mNotifyProgress;
    private DirectionalLayout mRemoveAll;
    private PhotoView mImage;
    private WebView mWebView;
    private InterceptionListener mInterceptionListener;

    public NotifyPageProvider(Context context) {
        this.context = context;
        notifyUtil = new NotifyUtil();
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        ComponentContainer container;
        if (i == 0) {
            container = (ComponentContainer) LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_notify, null, false);
            mSingLine = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_normal_singLine);
            mMoreLine = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_normal_moreLine);
            mMailbox = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_mailbox);
            mBigPic = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_bigPic);
            mCustomView = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_customview);
            mButtom = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_buttom);
            mProgress = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_progress);
            mNotifyProgress = (DirectionalLayout) container.findComponentById(ResourceTable.Id_notify_headUp);
            mRemoveAll = (DirectionalLayout) container.findComponentById(ResourceTable.Id_remove_all);

            mSingLine.setClickedListener(this);
            mMoreLine.setClickedListener(this);
            mMailbox.setClickedListener(this);
            mBigPic.setClickedListener(this);
            mCustomView.setClickedListener(this);
            mButtom.setClickedListener(this);
            mProgress.setClickedListener(this);
            mNotifyProgress.setClickedListener(this);
            mRemoveAll.setClickedListener(this);

            mImage = (PhotoView) container.findComponentById(ResourceTable.Id_which_img);
            mImage.isRecyclerView(true);
            mImage.setOnEnableListener(this);
        } else {
            container = (ComponentContainer) LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_me, null, false);

            mWebView = (ohos.agp.components.webengine.WebView) container.findComponentById(ResourceTable.Id_web_view);
            mWebView.setWebAgent(new WebAgent());
            mWebView.getWebConfig().setJavaScriptPermit(true);
            mWebView.load("https://gitee.com/");
        }
        // 检查componentContainer是否有显示并remove
        if (componentContainer.isComponentDisplayed()) {
            componentContainer.removeAllComponents();
        }
        componentContainer.addComponent(container);
        return componentContainer;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {

    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return false;
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_notify_normal_singLine:
                notifyUtil.notify_normal_singLine("双十一大优惠！！！",
                        "仿真皮肤充气娃娃，女朋友带回家!",
                        getPixelMap(ResourceTable.Media_tb_bigicon),
                        getIntentAgent(1), 1);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image1));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_normal_moreLine:
                notifyUtil.notify_normal_moreLine("朱立伦请辞国民党主席 副主席黄敏惠暂代党主席",
                        "据台湾“中央社”报道，国民党主席朱立伦今天(18日)向中常会报告，为败选请辞党主席一职，他感谢各位中常委的指教包容，也宣布未来党务工作由副主席黄敏惠暂代，完成未来所有补选工作。",
                        getPixelMap(ResourceTable.Media_netease_bigicon),
                        getIntentAgent(2), 2);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image2));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_mailbox:
                notifyUtil.notify_mailbox("冰冰",
                        setMailBoxList(),
                        getPixelMap(ResourceTable.Media_weixin),
                        getPixelMap(ResourceTable.Media_fbb_smallicon),
                        getIntentAgent(3), 3);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image3));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_bigPic:
//                ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_custom_pic, getContext()); // 创建ComponentProvider对象
//                componentProvider.setString(ResourceTable.Id_ongoing_card_text, "setText", "TextContent"); // 设置布局中的文本内容
                notifyUtil.notify_bigPic("已经抓取屏幕截图",
                        "触摸可查看您的屏幕截图",
                        getPixelMap(ResourceTable.Media_xc_smaillicon),
                        getPixelMap(ResourceTable.Media_screenshot),
                        getIntentAgent(4), 4);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image4));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_customview:
                notifyUtil.notify_customview(context,
                        ResourceTable.Layout_notify_customview,
                        ResourceTable.Id_custom_btn,
                        getPixelMap(ResourceTable.Media_yybao_smaillicon),
                        getIntentAgent(5), getIntentAgentNo(5), 5);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image5));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_buttom:
                notifyUtil.notify_button("系统更新已下载完毕",
                        "Ohos 2.0.0",
                        "以后再说",
                        "安装",
                        getPixelMap(ResourceTable.Media_ohos_bigicon),
                        getIntentAgent(6), getIntentAgentNo(6), 6);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image6));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_progress:
                notifyUtil.notify_progress(context,
                        "Ohos 2.0.0 下载",
                        "正在下载",
                        "下载完成",
                        getPixelMap(ResourceTable.Media_ohos_bigicon),
                        getIntentAgent(7), 7);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image7));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_notify_headUp:
                notifyUtil.notify_headUp("范冰冰",
                        "文明，今晚在希尔顿酒店2016号房哈",
                        "回复",
                        "拨打",
                        getPixelMap(ResourceTable.Media_hl_smallicon),
                        getPixelMap(ResourceTable.Media_fbb_smallicon),
                        getIntentAgent(8), getIntentAgentNo(8), 8);
                mImage.setPixelMap(getPixelMap(ResourceTable.Media_image8));
                mImage.setScale(1, 1);
                break;
            case ResourceTable.Id_remove_all:
                cancelAll();
                break;
        }
    }

    private PixelMap getPixelMap(int drawableId) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(drawableId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            ImageSource imageSource = ImageSource.create(drawableInputStream, sourceOptions);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            return imageSource.createPixelmap(decodingOptions);
        } catch (IOException | NotExistException e) {
            e.getMessage();
        } finally {
            if (drawableInputStream != null) {
                try {
                    drawableInputStream.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
        return null;
    }

    private ArrayList<String> setMailBoxList() {
        ArrayList<String> arrayListStr = new ArrayList<>();
        arrayListStr.add("文明,今晚有空吗？");
        arrayListStr.add("晚上跟我一起去玩吧?");
        arrayListStr.add("怎么不回复我？？我生气了！！");
        arrayListStr.add("我真生气了！！！！！你听见了吗!");
        arrayListStr.add("文明，别不理我！！！");
        return arrayListStr;
    }

    private IntentAgent getIntentAgent(int notificationId) {
        Intent intent = new Intent();
        // 指定要启动的Ability的BundleName和AbilityName字段
        // 将Operation对象设置到Intent中
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(context.getBundleName())
                .withAbilityName(OtherAbility.class.getName())
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
                .build();
        intent.setOperation(operation);
        intent.setParam("notificationId", notificationId);
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);
        // 定义请求码
        int requestCode = 300 + notificationId;
        // 设置flags
        List<IntentAgentConstant.Flags> flags = new ArrayList<>();
        flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
        // 指定启动一个有页面的Ability
        IntentAgentInfo paramsInfo = new IntentAgentInfo(requestCode, IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
        // 获取IntentAgent实例
        IntentAgent agent = IntentAgentHelper.getIntentAgent(context, paramsInfo);
        return agent;
    }

    private IntentAgent getIntentAgentNo(int notificationId) {
        Intent intent = new Intent();
        // 指定要启动的Ability的BundleName和AbilityName字段
        // 将Operation对象设置到Intent中
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(context.getBundleName())
                .withAbilityName(OtherAbility.class.getName())
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
                .build();
        intent.setOperation(operation);
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);
        // 定义请求码
        int requestCode = 200 + notificationId;
        // 设置flags
        List<IntentAgentConstant.Flags> flags = new ArrayList<>();
        flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
        // 指定启动一个有页面的Ability
        IntentAgentInfo paramsInfo = new IntentAgentInfo(requestCode, IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
        // 获取IntentAgent实例
        IntentAgent agent = IntentAgentHelper.getIntentAgent(context, paramsInfo);
        return agent;
    }

    private void cancelAll() {
        try {
            NotificationHelper.cancelAllNotifications();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onEnable(boolean b) {
        mInterceptionListener.interceptPageSlider(b);
    }

    /**
     * 判断是否PageSlider可以滑动的接口
     */
    public interface InterceptionListener {
        /**
         * 判断是否PageSlider可以滑动的方法
         *
         * @param isSlide 布尔值
         */
        void interceptPageSlider(boolean isSlide);
    }

    /**
     * 设置是否PageSlider可以滑动
     *
     * @param interception 回调接口
     */
    public void setInterceptionListener(InterceptionListener interception) {
        mInterceptionListener = interception;
    }
}
